var express = require('express');
var router = express.Router();
var { User, Doctor, Backstage, Dynamic, Reviews, Drug, Shop, ShopDrug } = require('../model/model')

router.get('/user',async(req,res)=>{
    let user = await User.find()
    let {name,age,sex,phone}=req.query
    if(name){
        user = user.filter(item=>item.name.includes(name))
    }
    if(age){
        user = user.filter(item=>item.age==age)
    }
    if(sex){
        user = user.filter(item=>item.sex==sex)
    }
    if(phone){
        user = user.filter(item=>item.phone==phone)
    }
    //分页
    let page=req.query.page||1
    let pagesize=req.query.pagesize||10
    let total=user.length
    user=user.slice((page-1)*pagesize,page*pagesize)
    res.send({
        code:200,
        user,
        page,
        pagesize,
        total
    })
})

router.post('/user',async(req,res)=>{
    User.create(req.body)
    res.send({
        code:200,
        msg:'添加成功'
    })
})

//上传病例，添加就诊医生
router.put('/user',async(req,res)=>{
    let name=req.body.name
    let user=await User.findOne({name})
    let arr=[...user.record]
    arr.push(req.body.record)
    await User.updateOne({name},{record:arr})
    
    let doctor_id=[...user.doctor_id]
    doctor_id.push(req.body.doctor_id)
    await User.updateOne({name},{doctor_id})

    let doctor=await Doctor.findOne({_id:req.body.doctor_id})
    let user_id=[...doctor.user_id]
    user_id.push(user._id)
    await Doctor.updateOne({_id:doctor._id},{user_id})

    res.send({
        code:200,
        msg:'上传成功'
    })
})

router.get('/doctor',async(req,res)=>{
    let doctor = await Doctor.find()
    res.send({
        code:200,
        doctor
    })
})
router.get('/drug',async(req,res)=>{
    let doctor = await Drug.find()
    //查找
    let name=req.query.name
    if(name){
        doctor=doctor.filter(item=>item.name.includes(name))
    }
    res.send({
        code:200,
        doctor
    })
})


router.post('/doctor',async(req,res)=>{
    Doctor.create(req.body)
    res.send({
        code:200,
        msg:'添加成功'
    })
})

router.get('/backstage',async(req,res)=>{
    let backstage = await Backstage.find()
    res.send({
        code:200,
        backstage
    })
})

router.post('/backstage',async(req,res)=>{
    Backstage.create(req.body)
    res.send({
        code:200,
        msg:'添加成功'
    })
})

router.post('/login',async(req,res)=>{
    let user = await Doctor.findOne(req.body)
    if(user){
        res.send({
            code:200,
            msg:'登录成功',
            user
        })
    }else{
        res.send({
            code:400,
            msg:'用户名或密码错误'
        })
    }
})


module.exports = router;
